package com.binfast.common.util;

import cn.hutool.core.convert.Convert;
import io.jsonwebtoken.Claims;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

public class UserUtils {
    private static final ThreadLocal<Object> THREAD_LOCAL_USER = new ThreadLocal<>();
    private static final String KEY_USER = "user";

    /**
     * 根据header中的token获取用户ID
     *
     * @param httpServletRequest
     * @return 用户ID
     */
    public static Long getUserId(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtil.parseJwtToken(token);
        Long userId = Convert.toLong(claims.get("userId"),0l) ;
        return userId;
    }

    /**
     * 根据token获取用户ID
     *
     * @param token
     * @return 用户ID
     */
    public static Long getUserId(String token) {
        Claims claims = JwtUtil.parseJwtToken(token);
        Long userId = Convert.toLong(claims.get("userId"),0l) ;
        return userId;
    }

      /**
     * 根据header中的token获取用户ID
     *
     * @param httpServletRequest
     * @return 用户ID
     */
    public static UUID getClientId(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("token");
        Claims claims = JwtUtil.parseJwtToken(token);
        UUID clientId = UUID.fromString( Convert.toStr(claims.get("userId"),""));
        return clientId;
    }


    /**
     * 设置用户信息
     *
     */
    public static void setUser(Object user) {
        THREAD_LOCAL_USER.set(user);
    }

    /**
     * 从threadlocal 获取用户
     */
    public static Object getUser() {
        return THREAD_LOCAL_USER.get();
    }

    public static void clearAllUserInfo() {
        THREAD_LOCAL_USER.remove();
    }
}
